package com.zone.sdk.module.appstore.http;

import com.zone.sdk.common.http.Content;
import com.zone.sdk.common.http.OkHttpManager;
import com.zone.sdk.common.http.apimock.ApiMock;
import com.zone.sdk.common.http.apimock.fastjson.FastJsonConverterFactory;
import com.zone.sdk.common.http.apimock.interceptor.MockInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * @Author: pkqlqx
 * @CreateDate: 2021/12/5 14:30
 * @Description:
 */
public class AppStoreOkHttpManager extends OkHttpManager {

    private static AppStoreOkHttpManager instance;

    private static HeaderInterceptor headerInterceptor;

    private static BodyInterceptor bodyInterceptor;

    protected OkHttpClient mOkHttpClient;
    protected Retrofit mRetrofit;
    private final  String baseUrl;

    private AppStoreOkHttpManager(String baseUrl){
        super();
        headerInterceptor = new HeaderInterceptor();
        bodyInterceptor = new BodyInterceptor();
        this.baseUrl = baseUrl;
    }

    public synchronized static AppStoreOkHttpManager getInstance(String baseUrl){
        if (instance == null){
            instance = new AppStoreOkHttpManager(baseUrl);
        }
        return instance;
    }

    public void setAuthorization(String authorization) {
        headerInterceptor.addParam(Content.AUTHORIZATION_APPSTORE, Content.AUTHORIZATION_APPSTORE_BEARER+authorization);
    }

    @Override
    public <T> T build(Class<T> service) {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
                .connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS);
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        if (ApiMock.isMock()){
            builder.addInterceptor(new MockInterceptor());
        }else {
            builder.addInterceptor(loggingInterceptor);
            //        HeaderInterceptor headerInterceptor = new HeaderInterceptor();
            builder.addInterceptor(headerInterceptor);
            builder.addInterceptor(bodyInterceptor);
        }
        mOkHttpClient = builder.build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(mOkHttpClient)
                .build();
        return mRetrofit.create(service);
    }
}
